package com.yyj.web.controller;

import com.yyj.common.BaseResponse;
import com.yyj.constant.ReturnCode;
import com.yyj.exception.RequestParamCheckingException;
import com.yyj.util.RspUtils;
import com.yyj.util.helper.InvokeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author leezp
 * @create 2018-02-05 15:28
 **/
@Component
public class BaseController {

    public static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    InvokeHelper invokeHelper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Autowired
    public HttpSession session;
    
    /**
     * 校验请求参数
     * @throws RequestParamCheckingException
     */
    public void checkRequestParams(BindingResult result) throws RequestParamCheckingException {
        if(result.hasErrors()){
            List<ObjectError> resultErrors = result.getAllErrors();
            throw new RequestParamCheckingException(resultErrors.get(0).getDefaultMessage());
        }
    }

    public <T> BaseResponse<T> formatErrorMsg(T data, Exception e) {
        logger.error("Exception:", e);
        return RspUtils.error(data, e.getMessage(), ReturnCode.NORMAL_ERROR );
    }

}
